﻿using RFBR.Core.Infrastructure;
using RFBR.Core.Infrastructure.XmlModels;
using RFBR.Core.Infrastructure.Models.Structure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml.Serialization;
using Xml = RFBR.Core.Infrastructure.XmlModels;
using System.Xml;

namespace RFBR.Core.Helpers
{
    public static class KnowledgeBaseHelper
    {
        public static IKnowledgeBase KnowledgeBaseDeserialize(Stream file)
        {
            Xml.KnowledgeBase kbase = null;

            XmlSerializer serializer = new XmlSerializer(typeof(Xml.KnowledgeBase));

            StreamReader reader = new StreamReader(file);
            kbase = (Xml.KnowledgeBase)serializer.Deserialize(reader);
            reader.Close();
            return XmlParser.Instance.GetModel(kbase);
        }

        public static Stream KnowledgeBaseSerialize(IKnowledgeBase kb)
        {
            object schema = XmlParser.Instance.GetSchema(kb);

            XmlSerializer serializer = new XmlSerializer(typeof(Xml.KnowledgeBase));
            //StringWriter textWriter = new StringWriter();
            MemoryStream stream = new MemoryStream();
            //StreamWriter writer = new StreamWriter(stream);
            //serializer.Serialize(textWriter, schema);
            serializer.Serialize(stream, schema);
            //return textWriter.ToString();
            stream.Position = 0;
            return stream;
        }

        public static IKnowledgeBase CreateNewKnowledgeBase()
        {
            return KnowledgeBaseManager.New();
        }

        public static IFrame UpdateFrame(IKnowledgeBase model, dynamic frame)
        {
            return XmlParser.Instance.UpdateFrame(model, frame);
        }

        public static dynamic GetEntityJSON(IEntity entity)
        {
            switch (entity.Type)
            {
                case EntityType.Frame:
                    return new
                    {
                        entity.Id
                    };
                case EntityType.Variable:
                    IVariable variable = (IVariable)entity;
                    return new
                    {
                        variable.Id,
                        Domain = variable.Domain.Items.Select(it=>it.ToString()),
                        variable.Value
                    };
                case EntityType.Custom:
                default:
                    ICustomObject val = (ICustomObject)entity;
                    return new
                    {
                        val.Id,
                        val.Value
                    };
            }
        }
    }
}
